﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Quartz;
using Quartz.Impl;
using Quartz.Spi;
using System;

namespace Bean.Quartz.Core
{
    /// <summary>
    /// 定时任务注入
    /// </summary>
    public static class QuartzExtentsions
    {
        /// <summary>
        /// 配置
        /// </summary>
        /// <param name="services"></param>
        public static void AddQuartz(this IServiceCollection services)
        {
            services.AddSingleton<QuartzStartup>();
            services.AddSingleton<ISchedulerFactory, StdSchedulerFactory>();
            services.AddSingleton<IJobFactory, QuartzIocFactory>();
        }
        
        
        /// <summary>
        /// 使用
        /// </summary>
        /// <param name="app"></param>
        /// <param name="action"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseQuartz(this IApplicationBuilder app, Action<QuartzStartup> action = null)
        {
            QuartzStartup startup = app.ApplicationServices.GetService<QuartzStartup>();
            var lifetime = app.ApplicationServices.GetService<IHostApplicationLifetime>();

            lifetime.ApplicationStarted.Register(() =>
            {
                startup.StartAsync().Wait();
                action?.Invoke(startup);
            });

            lifetime.ApplicationStopping.Register(() =>
            {
                startup.StopAsync().Wait();
            });

            return app;
        }
    }
}
